Skip to content

gh-149473: Emit audit event on calling os.environ.clear()#149768

Open
vstinner wants to merge 1 commit into
python:mainfrom
vstinner:audit_clearenv
Open

gh-149473: Emit audit event on calling os.environ.clear()#149768
vstinner wants to merge 1 commit into
python:mainfrom
vstinner:audit_clearenv

Conversation

@vstinner
Copy link
Copy Markdown
Member

@vstinner vstinner commented May 13, 2026

@vstinner
Copy link
Copy Markdown
Member Author

cc @picnixz

@read-the-docs-community
Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #32670664 | 📁 Comparing f86414a against main (94df625)

  🔍 Preview build  

3 files changed
± library/audit_events.html
± library/os.html
± whatsnew/changelog.html

@@ -0,0 +1,2 @@
Calling ``os.environ.clear()`` now emits ``os._clearenv`` auditing event.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The event is only emitted if we use the C implementation right? Otherwise os.environ.clear() is implemented in pure Python. I don't know if you want to update the Python implementation as well though.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If os._clearenv() is not available, os.environ.clear() emits one audit event os.unsetenv per removed variable. Example:

import os, sys

os.environ.clear()
os.environ['key1'] = 'value1'
os.environ['key2'] = 'value2'

def hook(*args):
    print("audit:", args)
sys.addaudithook(hook)
os.environ.clear()

Output with os._clearenv() and this change:

audit: ('os._clearenv', ())

Output without os._clearenv():

audit: ('os.unsetenv', (b'key1',))
audit: ('os.unsetenv', (b'key2',))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be explicitly documented actually. With the new docs, I think people could expect os.environ.clear() to emit _clearenv unconditionally. I also see that we say that unsetenv is called whenever we call os.environ.clear() but that's not entirely accurate either.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting core review needs backport to 3.15 pre-release feature fixes, bugs and security fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants